package web.converter;

import org.apache.log4j.Logger;
import org.springframework.core.convert.converter.Converter;

import java.text.SimpleDateFormat;
import java.util.Date;

public class String2DateConverter implements Converter<String, Date> {
    private Logger logger = Logger.getLogger(String2DateConverter.class);
    private String datePattern;

    /**
     * 一个日期格式参数的构造函数
     * @param datePattern
     */
    public String2DateConverter(String datePattern) {
        logger.info("加载 String2DateConverter");
        this.datePattern = datePattern;
    }

    /**
     * 具体的字符串转日期的方法
     * @param s
     * @return
     */
    @Override
    public Date convert(String s) {
        Date date= null;
        try {
            date= new SimpleDateFormat(datePattern).parse(s);
            logger.info("String2DateConverter converter date:"+date);
        } catch (Exception e) {
            logger.error("日期转换失败", e);
            throw new RuntimeException("日期转换失败", e);
        }
        return date;
    }
}
